package utils

import (
	"errors"
	"fresh-shop-gin/config"
	"time"

	"github.com/golang-jwt/jwt/v5"
)

// 自定义Claims
type CustomClaims struct {
	UserId   int64  `json:"userId"`
	Username string `json:"userName"`
	jwt.RegisteredClaims
}

// 生成Token
func GenerateToken(userId int64, username string) (string, error) {
	// 获取config配置
	cfg, err := config.LoadConfig()
	if err != nil {
		panic(err)
	}
	claims := CustomClaims{
		UserId:   userId,
		Username: username,
		RegisteredClaims: jwt.RegisteredClaims{
			ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(cfg.JWT.Expires) * time.Hour)),
			Issuer:    cfg.JWT.Issuer,
		},
	}

	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	return token.SignedString([]byte(cfg.JWT.Secret))
}

// 解析Token
func ValidateToken(tokenString string) (*CustomClaims, error) {
	// 获取config配置
	cfg, err := config.LoadConfig()
	if err != nil {
		panic(err)
	}
	token, err := jwt.ParseWithClaims(tokenString, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, errors.New("意外签名方法")
		}
		return []byte(cfg.JWT.Secret), nil
	})

	if claims, ok := token.Claims.(*CustomClaims); ok && token.Valid {
		return claims, nil
	}

	return nil, err
}
